#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "cJSON.h"

#define APPID "17846293"
#define APPKEY "5OGpgFrroMaief5aTNQGMQPD"
#define SECRETKEY "0PxiO567mTTfQBPv1PQPsTzBOCAUA08j"

CURL *curl;

char *get_token(const char *appkey, const char *secretkey)
{
	char *request;
	char *response;
	size_t resplen;

	asprintf(&request, "grant_type=client_credentials&client_id=%s&client_secret=%s", appkey, secretkey);
	FILE *fp = open_memstream(&response, &resplen);
	if (!fp)
		perror("open_memstream");
	curl_easy_setopt(curl, CURLOPT_URL, "http://openapi.baidu.com/oauth/2.0/token");
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
	CURLcode res = curl_easy_perform(curl);
	if (res != CURLE_OK)
		puts(curl_easy_strerror(res));
	fclose(fp);

	cJSON *resp = cJSON_Parse(response);
	//puts(cJSON_Print(resp));
	cJSON *token = cJSON_GetObjectItemCaseSensitive(resp, "access_token");

	char *retval = strdup(token->valuestring);

	free(response);
	cJSON_Delete(resp);

	return retval;
}

int poet_init()
{
	curl_global_init(CURL_GLOBAL_ALL);
	curl = curl_easy_init();
	return 0;
}

void poet_cleanup()
{
	curl_easy_cleanup(curl);
	curl_global_cleanup();
}

void make_poem(char *input)
{
	char * url;
	char *request;
	char *response;
	size_t resplen;
	struct curl_slist *header = NULL;
	char* token = get_token(APPKEY, SECRETKEY);

	asprintf(&url, "https://aip.baidubce.com/rpc/2.0/creation/v1/poem?access_token=%s", token);
	free(token);
	asprintf(&request, "{\"text\": \"%s\", \"index\": 0}", input);
	puts(request);

	FILE *fp = open_memstream(&response, &resplen);
	if (!fp)
		perror("open_memstream");
	curl_easy_setopt(curl, CURLOPT_URL, url);
	header = curl_slist_append(header, "Content-Type: application/json");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
	CURLcode res = curl_easy_perform(curl);
	if (res != CURLE_OK)
		puts(curl_easy_strerror(res));
	fclose(fp);

	cJSON *resp = cJSON_Parse(response);
	puts(cJSON_Print(resp));

	cJSON *poem = cJSON_GetObjectItemCaseSensitive(resp, "poem");
	cJSON *obj;

	cJSON_ArrayForEach(obj, poem)
	{
		cJSON *title = cJSON_GetObjectItemCaseSensitive(obj, "title");
		cJSON *content = cJSON_GetObjectItemCaseSensitive(obj, "content");
		printf("%s\n", title->valuestring);
		printf("%s\n", content->valuestring);
	}

	free(response);
	cJSON_Delete(resp);
}

int main(int argc, char** argv)
{
	poet_init();
	make_poem(argv[1]);
	poet_cleanup();

	return 0;
}
